
$(function () {

    var fundType = $("select[name=fundType]"),
        fundOperation = $("select[name=fundOperation]"),
        fundStatus = $("select[name=fundStatus]"),
        pnrAccountName = $("select[name=pnrAccountName]"),
        dateRangePicker = $('#daterangepicker'),
        names = {};
    /**
     * 初始化下拉列表
     */
    var downArrow = ' <b class="caret"></b>';
    
    var initDateRangePicker = function () {
        var rangePast = {
            '今天': [moment(), moment()],
            '昨天': [moment().subtract('days', 1), moment().subtract('days', 1)],
            '最近7天': [moment().subtract('days', 6), moment()],
            '最近30天': [moment().subtract('days', 29), moment()],
            '本月': [moment().startOf('month'), moment().endOf('month')],
            '上个月': [moment().subtract('month', 1).startOf('month'), moment().subtract('month', 1).endOf('month')]
        };
        var rangeFuture = {
            '今天': [moment(), moment()],
            '未来7天': [moment(), moment().add('days', 6)],
            '未来30天': [moment(), moment().add('days', 29)],
            '未来60天': [moment(), moment().add('days', 59)],
            '本月': [moment().startOf('month'), moment().endOf('month')],
            '下个月': [moment().add('month', 1).startOf('month'), moment().add('month', 1).endOf('month')]
        };

        dateRangePicker.daterangepicker({
            ranges: status === "repayed" ? rangePast : rangeFuture,
            startDate: status === "repayed" ? moment().subtract('days', 29) : moment(),
            endDate: status === "repayed" ? moment() : moment().add('days', 29),
            applyClass: "btn-primary btn-block",
            cancelClass: "btn-block",
            format: "YYYY/MM/DD",
            locale: {
                applyLabel: '确定',
                clearLabel: "取消",
                fromLabel: '开始时间',
                toLabel: '结束时间',
                weekLabel: '周',
                customRangeLabel: '选择范围',
                daysOfWeek: "日_一_二_三_四_五_六".split("_"),
                monthNames: "一月_二月_三月_四月_五月_六月_七月_八月_九月_十月_十一月_十二月".split("_"),
                firstDay: 0
            },
            opens: "left"
        });


        var formatDate = function (date) {
            return $.format.date(new Date(date), "yyyy/MM/dd");
        };
        // 根据状态设定初始日期
        var defaultDate = status === 'repayed'
            ? formatDate(moment().subtract('days', 29)) + ' - ' + formatDate(moment())
            : formatDate(moment()) + ' - ' + formatDate(moment().add('days', 29));

        dateRangePicker.val(defaultDate);
        $(".daterangepicker .ranges ul li:last").hide();
        $(".daterangepicker .ranges .daterangepicker_start_input").remove();
        $(".daterangepicker .ranges .daterangepicker_end_input").remove();
        $(".daterangepicker .ranges .cancelBtn").remove();
    };
    
    /**
     * 加载平台资金账户信息
     */
    $.get("fund/queryPlatformAccounts", function (map) {
        var config = map.config;
        names[config.accounts.primaryAccount.id] = config.accounts.primaryAccount.name;
        names[config.accounts.reserveAccount.id] = config.accounts.reserveAccount.name;
        names[config.accounts.feeAccount.id] = config.accounts.feeAccount.name;

        pnrAccountName.append($("<option></option>").attr("value", config.accounts.primaryAccount.id).text(config.accounts.primaryAccount.name));
        pnrAccountName.append($("<option></option>").attr("value", config.accounts.reserveAccount.id).text(config.accounts.reserveAccount.name));
        pnrAccountName.append($("<option></option>").attr("value", config.accounts.feeAccount.id).text(config.accounts.feeAccount.name));

        $('.multiple-select').multiselect({
            includeSelectAllOption: true,
            selectAllText: '全选',
            buttonText: function (options, select) {
                if (options.length === 0) {
                    return '全部' + downArrow;
                } else if (options.length === 0) {
                    return $(options[0]).html() + downArrow;
                } else {
                    return $(options[0]).html() + ' ...' + downArrow;
                }
            },
            buttonClass: 'btn btn-default btn-sm',
            allSelectedText: '全部'
        });

        $("#multiple-select-loading").remove();
        $("#multiple-select-filter").removeClass("hidden");

        initFundHistoryTable();
    });

    /**
     * 初始化资金记录列表
     */
    var initFundHistoryTable = function () {
        var table = $('#fundHistoryList').DataTable({
            "processing": true,
            "serverSide": true,
            "bSort": false,
            "ajax": {
                "url": "fund/getPlatformFundRecord",
                "data": function (d) {
                    var selected = pnrAccountName.val() || [];
                    d.pnrAccount = selected.join(',');
                    selected = fundType.val() || []
                    d.fundType = selected.join(',');
                    selected = fundStatus.val() || []
                    d.fundStatus = selected.join(',');
                    selected = fundOperation.val() || []
                    d.fundOperation = selected.join(',');
                    var dateRange = dateRangePicker.val().split(" - ");
                    d.startTime = new Date(dateRange[0]);
                    var endTime = moment(dateRange[1], "YYYY-MM-DD").endOf('day');
                    d.endTime = new Date(endTime);
                },
                "type": "POST"
            },
            "columns": [
                {"data": "orderId"},
                {"data": "transId"}, //transId
                {"data": "account"}, // 账户代码
                {"data": "account"}, // 账户名称
                {"data": "amount"},
                {"data": "type"},
                {"data": "operation"},
                {"data": "status"},
                {"data": "recordTime"},
                {"data": "description"}
            ],
            "aoColumnDefs": [{
                    "targets": 1, //流水号
                    "visible": false
                }, {
                    "targets": 3, // 账户名称
                    "visible": false,
                    "mRender": function (data, type, row) {
                        if (data in names) {
                            return names[data];
                        } else {
                            return "";
                        }
                    }
                }, {
                    "targets": 4, //金额
                    "mRender": function (data, type, row) {
                        return $.number(data, 2);
                    }
                }, {
                    "targets": 5, //资金类型
                    "mRender": function (data, type, row) {
                        return sysFundType[data];
                    }
                }, {
                    "targets": 6, //操作类型
                    "mRender": function (data, type, row) {
                        return sysFundOperation[data];
                    }
                }, {
                    "targets": 7, //资金状态
                    "mRender": function (data, type, row) {
                        return sysFundStatus[data];
                    }
                }, {
                    "targets": 8, //投标时间
                    "searchable": false,
                    "mRender": function (data, type, row) {
                        return $.format.date(new Date(data), "yy/MM/dd HH:mm");
                    }
                }],
            "order": [8, 'desc'],
            "oLanguage": chinese,
            "language": {
                "decimal": ",",
                "thousands": ",",
            },
            "iDisplayLength": 20,
            "aLengthMenu": [
                [5, 10, 20, 50, 100, -1],
                [5, 10, 20, 50, 100, "全部"]
            ],
            //"sDom": 't<"dt-panelfooter clearfix"lp>',
            "sDom": '<"dt-panelmenu clearfix"l<"pull-right"T>r>t<"dt-panelfooter clearfix"ip>',
            "oTableTools": {
                "aButtons": [{
                        "sExtends": "xls",
                        "sButtonText": "导出为Excel"
                    }
                ],
                "sSwfPath": root_path + "/js/plugins/datatables/extensions/TableTools/swf/copy_csv_xls_pdf.swf"
            },
            "initComplete": function (settings, json) {
                $("#fundCount").text(json.recordsTotal);
            }
        });
        /**
         * 搜索按钮响应事件
         */
        $('#searchFundRecord').on('click', function () {
            table.ajax.reload();
        });

        /**
         * 显示/隐藏列
         */
        $('label.toggle-label input[type=checkbox]').on('change', function (e) {
            var checked = $(this).prop("checked"),
                col_index = $(this).attr('data-column'),
                column = table.column(col_index);

            if (checked) {
                column.visible(true);
            } else {
                column.visible(false);
            }
        });
    };
    initDateRangePicker();
});